/****************************************************************************
	This file is part of Basqet.

	Basqet is free software: you can redistribute it and/or modify
	it under the terms of the GNU General Public License as published by
	the Free Software Foundation, either version 3 of the License, or
	(at your option) any later version.

	Basqet is distributed in the hope that it will be useful,
	but WITHOUT ANY WARRANTY; without even the implied warranty of
	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
	GNU General Public License for more details.

	You should have received a copy of the GNU General Public License
    along with Basqet.  If not, see <http://www.gnu.org/licenses/>.

****************************************************************************/


#include "mainwindow.h"
#include "basketmanager.h"

#include "richtextedittoolbar.h"
#include "noteobjecttoolbar.h"

#include "eventfilterundoredo.h"
#include "eventfiltercontextmenu.h"
#include "notepadpage.h"

#include "settings.h"

#include "backupworker.h"

#include "editsettingsdialog.h"
#include "aboutdialog.h"
#include "timeanddatedisplay.h"

#include "filedialog.h"

#include <QFileInfo>
#include <QSettings>
#include <QSystemTrayIcon>
#include <QMessageBox>

#include <QLabel>

#include <QStatusBar>

#include <QtDebug>




MainWindow::MainWindow(QWidget *parent)
	: QMainWindow(parent),
	mSystemtrayIcon(new QSystemTrayIcon(this)),
	mRichTextEditorToolbar(new RichTextEditToolBar(this)),
	mNoteObjectToolbar(new NoteObjectToolBar(this)),
	mRichTextBroker(&ui, mRichTextEditorToolbar.data()),
	mNoteObjectBroker(&ui,mNoteObjectToolbar.data())
{
	setWindowIcon(QIcon(":/basqet.png"));
	setupApplication();

	startBackupThread();

	ui.setupUi(this);

	mSystemtrayIcon->setIcon(this->windowIcon());
	mSystemtrayIcon->show();

	connect(mSystemtrayIcon, SIGNAL(activated(QSystemTrayIcon::ActivationReason)), this, SLOT(trayIconClicked()));

	addToolBar(mRichTextEditorToolbar.data());
	addToolBar(mNoteObjectToolbar.data());

	QStatusBar* sBar = new QStatusBar(this);

	setStatusBar(sBar);
	sBar->addPermanentWidget(new TimeAndDateDisplay(this));


	connect(ui.pOutlineTree, SIGNAL(LoadBasket(QFileInfo)), this, SLOT(LoadBasket(QFileInfo)));
	connect(ui.pOutlineTree, SIGNAL(aboutToChangeBasket(QFileInfo)), this, SLOT(basketAboutToChange()));
	connect(ui.pOutlineTree, SIGNAL(basketChanged(QFileInfo,QFileInfo)), this, SLOT(basketIsChanged()));


	connect(ui.actionSettings, SIGNAL(triggered()), this, SLOT(showSettingsDialog()));
	connect(ui.actionExit, SIGNAL(triggered()), this, SLOT(close()));
	connect(ui.actionExport_Page, SIGNAL(triggered()), this, SLOT(actionExport()));

	connect(ui.actionAbout_Basqet, SIGNAL(triggered()), this, SLOT(showAboutDialog()));
	connect(ui.actionAbout_Qt, SIGNAL(triggered()), this, SLOT(showAboutQtDialog()));

	connect(QCoreApplication::instance(), SIGNAL(aboutToQuit()), this, SLOT(aboutToQuit()));

}

MainWindow::~MainWindow()
{

}

void MainWindow::LoadBasket(QFileInfo newPath)
{
	statusBar()->showMessage(QString(tr("Loading basket %1.")).arg(newPath.fileName()), 5000);
	// Unload any loaded basket after saving it first.
	if (mCurrentBasket)
	{
		mCurrentBasket->actionSave();
		delete mCurrentBasket;
	}
		void outlineContextMenu();


	// Create the new basket and connect signals
	mCurrentBasket = new BasketManager(newPath.filePath());
	connect(ui.actionSave, SIGNAL(triggered()), mCurrentBasket.data(), SLOT(actionSave()));
	connect(ui.actionPrint_XML, SIGNAL(triggered()), mCurrentBasket.data(), SLOT(actionPrintXML()));

	ui.pNotePadScrollArea->setWidget(mCurrentBasket->getNotePadPage());

	connect(mCurrentBasket->getNotePadPage(), SIGNAL(activated(QObject*,UICapabilities)), this, SLOT(activated(QObject*,UICapabilities)));
	connect(mCurrentBasket->getNotePadPage(), SIGNAL(deActivated(QObject*,UICapabilities)), this, SLOT(deActivated(QObject*,UICapabilities)));

	// Now the main UI widgeets are setup, lets open the basket and populate it from file
	mCurrentBasket->openBasket();

	EventFilterUndoRedo* filter = new EventFilterUndoRedo();
	filter->installIn(ui.pNotePadWidget, mCurrentBasket->getCommandManager().data());

	// Enable menu-items shown only when basket is loaded
	ui.actionExport_Page->setEnabled(true);



}


void MainWindow::basketAboutToChange()
{
	if (mCurrentBasket)
		mCurrentBasket->actionSave();

}


void MainWindow::basketIsChanged()
{
	if (mCurrentBasket)
	{
		if (!mCurrentBasket->verifyBasket())
		{
			mCurrentBasket->getNotePadPage()->hide();
			delete mCurrentBasket;
		}
	}
}

void MainWindow::activated(QObject* object ,UICapabilities capabilities)
{
	qDebug() << "MainUI:: Activated";

	mRichTextBroker.Connect(object, capabilities);
	mNoteObjectBroker.Connect(object, capabilities);

}

void MainWindow::deActivated(QObject* object,UICapabilities capabilities)
{
	qDebug() << "MainUI:: DeActivated";
	mRichTextBroker.Disconnect(object, capabilities);
	mNoteObjectBroker.Disconnect(object, capabilities);

}

void MainWindow::aboutToQuit()
{
	qDebug() << "MainWindow::about to quit";

	if (mCurrentBasket)
		mCurrentBasket->actionSave();
}


void MainWindow::setupApplication()
{

    QCoreApplication::setOrganizationName("Basqet");

#ifdef QT_DEBUG
    QCoreApplication::setApplicationName("Basqet_debug");
#else
    QCoreApplication::setApplicationName("Basqet");
#endif


	QSettings	settings;


	if (!settings.contains(SETTING_DATA_ROOT))
	{
		QString path = QDir::home().filePath("Basqet");
		settings.setValue(SETTING_DATA_ROOT, QVariant(path));
	}

	if (!settings.contains(SETTING_BACKUP_ROOT))
	{
		QString path = QDir::home().filePath("BasqetBackups");
		settings.setValue(SETTING_BACKUP_ROOT, QVariant(path));
	}

	if (!settings.contains(SETTING_DO_BACKUPS))
	{
		settings.setValue(SETTING_DO_BACKUPS, QVariant(true));
	}

	if (!settings.contains(SETTING_NO_OF_BACKUPS))
	{
		settings.setValue(SETTING_NO_OF_BACKUPS, QVariant(10));
	}


}

void MainWindow::startBackupThread()
{
	BackupWorker* worker = new BackupWorker;
	worker->start();
}


void MainWindow::showSettingsDialog()
{
	if (!mSettingsDialog)
	{
		mSettingsDialog = new EditSettingsDialog(this);

	}
	mSettingsDialog->show();

}



void MainWindow::showAboutDialog()
{
	if (!mAboutDialog)
	{
		mAboutDialog = new AboutDialog(this);

	}

	mAboutDialog->show();

}

void MainWindow::showAboutQtDialog()
{
	QMessageBox::aboutQt(this);

}

void MainWindow::actionExport()
{
	qDebug() << "Export is called";

	QString filter;
	QString fileName = FileDialog::getSaveFileName(this,
											 tr("Export NotePage to File:"),
											 QDir::homePath(),
                                             tr("HTML-Page (*.html);;Plain text (*.txt);;Open Document Format (*.odt)"),
											 &filter);


	QFileInfo	fileInfo(fileName);

	QString suffix = fileInfo.suffix().toLower();
	qDebug() << "Suffix is: " << suffix;

	if (suffix != "html" && suffix != "odf" && suffix != "txt")
	{
		qDebug() << "Appending suffix to filename based on selected filter";
        if (filter.contains("*.html") && !fileName.endsWith(".html", Qt::CaseInsensitive))
			fileName.append(".html");
        else if (filter.contains("*.odt") && !fileName.endsWith(".odt", Qt::CaseInsensitive))
            fileName.append(".odt");
        else if (filter.contains("*.txt") && !fileName.endsWith(".txt", Qt::CaseInsensitive))
			fileName.append(".txt");

	}


	qDebug() << "Export file to: " << fileName;
	mCurrentBasket->actionExportTo(fileName);


}


void MainWindow::trayIconClicked()
{
	qDebug() << "TrayIcon Clicked";

	if (this->isHidden())
	{
		this->setHidden(false);
		this->activateWindow();
	}
	else
	{
		this->setHidden(true);
	}

}

